View components are similar to partial views in that they allow you to reduce repetitive code, but they're appropriate for view content that requires code to run on the server in order to render the webpage. View components are useful when the rendered content requires database interaction, such as for a website shopping cart. View components aren't limited to model binding in order to produce webpage output.
In Razor Pages, the application of ViewStart.cshtml
and ViewImports.cshtml
is governed by their location in the folder hierarchy. These files are automatically discovered and applied by ASP.NET Core's Razor engine based on the folder structure.
ViewStart.cshtml
Works in Razor PagesGlobal Scope:
ViewStart.cshtml
file placed in the root of the Pages
folder applies to all Razor Pages in the project.Pages/ ├── _ViewStart.cshtml ├── Index.cshtml ├── About.cshtml
If _ViewStart.cshtml
contains:@{ Layout = "_Layout"; }
Index.cshtml
and About.cshtml
will use the _Layout
layout.Local Override:
ViewStart.cshtml
exists in a subfolder, it overrides the ViewStart.cshtml
in the parent folder for that subfolder and its descendants.Pages/ ├── _ViewStart.cshtml ├── Admin/ │ ├── _ViewStart.cshtml │ ├── Dashboard.cshtml └── Index.cshtml
_ViewStart.cshtml
in Pages/Admin/
will apply to Dashboard.cshtml
._ViewStart.cshtml
in the root will apply to Index.cshtml
.ViewImports.cshtml
Works in Razor PagesViewImports.cshtml
file placed in the root of the Pages
folder applies to all Razor Pages in the project. Pages/ ├── _ViewImports.cshtml ├── Index.cshtml ├── Contact.cshtml
_ViewImports.cshtml
contains:@using MyApp.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Index.cshtml
and Contact.cshtml
will have access to the MyApp.Models
namespace and the Tag Helpers.ViewImports.cshtml
file in a subfolder adds to or overrides the settings from the parent folder.Pages/ ├── _ViewImports.cshtml ├── Admin/ │ ├── _ViewImports.cshtml │ ├── Dashboard.cshtml └── Index.cshtml
@using
directives and Tag Helpers in Pages/Admin/_ViewImports.cshtml
will only apply to Dashboard.cshtml
.Pages/_ViewImports.cshtml
still applies to Index.cshtml
.ViewStart.cshtml
and ViewImports.cshtml
in a closer (nested) folder override or extend those in parent folders.ViewStart.cshtml
and ViewImports.cshtml
.Tag Helpers are server-side components in ASP.NET Core that help you generate and manipulate HTML elements using a natural and familiar syntax that resembles standard HTML.
Anchor Tag Helper (<a>
)
<a asp-controller="Home" asp-action="About" class="btn btn-primary">Go to About</a>
asp-controller
: Specifies the controller (Home
).asp-action
: Specifies the action (About
).<a href="/Home/About" class="btn btn-primary">Go to About</a>
Form Tag Helper
<form asp-controller="Account" asp-action="Login" method="post"> <input type="text" name="username" /> <button type="submit">Login</button> </form>
action
attribute based on the controller and action.*Input Tag Helper
<input asp-for="UserName" class="form-control" />
asp-for
: Binds the input element to the UserName
property of the model.Validation Tag Helpers
<span asp-validation-for="Email" class="text-danger"></span>
Email
property.asp-controller
or asp-for
.Tag Helpers are enabled globally in Razor views by default using the _ViewImports.cshtml
file:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
HTML Helpers are server-side C# methods that generate HTML elements dynamically. They are written in Razor syntax (@Html.*
) and allow you to create UI components programmatically.
Anchor Links (Html.ActionLink
)
@Html.ActionLink("Go to About", "About", "Home", null, new { @class = "btn btn-primary" })
<a href="/Home/About" class="btn btn-primary">Go to About</a>
Forms (Html.BeginForm
)
razor
@using (Html.BeginForm("Login", "Account", FormMethod.Post)) { @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" }) <button type="submit">Login</button> }
<form action="/Account/Login" method="post"> <input class="form-control" id="UserName" name="UserName" type="text" value=""> <button type="submit">Login</button> </form>
Input Fields (Html.TextBoxFor
)
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
<input class="form-control" id="Email" name="Email" type="text" value="">
Validation Messages
@Html.ValidationMessageFor(m => m.Email, null, new { @class = "text-danger" })
Email
property.System.Web.Mvc.HtmlHelper
class.Feature | Tag Helpers | HTML Helpers |
---|---|---|
Syntax | HTML-like attributes | C# method calls |
Readability | Cleaner and more intuitive | Less readable in complex scenarios |
Usage | Uses attributes like asp-for |
Uses Razor methods like Html.TextBox |
Configuration | Requires _ViewImports.cshtml setup |
No special configuration required |
Flexibility | Easier to extend and customize | More explicit but less integrated |
Examples | <input asp-for="Email" /> |
@Html.TextBoxFor(m => m.Email) |
ViewData
is of type ViewDataDictionary
) that allows storing data as key-value pairs.ViewData["Key"] = value;
dynamic
keyword internally) that provides a more flexible way to pass data without needing a strongly typed key.ViewBag.Key = value;
ViewBag.Key
) which feels more natural in many cases.ViewData
—runtime errors will occur if you try to access a non-existing property.Both ViewData
and ViewBag
store their data in the same place internally: the ViewData
dictionary.
ViewBag.Key
, it's actually stored in the ViewData["Key"]
dictionary.ViewData["Key"]
and ViewBag.Key
refers to the same underlying data, so they are interchangeable.For example:
csharp
Copy code
ViewData["Message"] = "Hello, ViewData!";
ViewBag.Message = "Hello, ViewBag!";
// This works because they share the same storage:
string msgFromViewData = ViewData["Message"].ToString(); // "Hello, ViewBag!"
string msgFromViewBag = ViewBag.Message; // "Hello, ViewBag!"
The ViewBag
uses the dynamic
type in C#, which means properties on the ViewBag
do not need to be declared beforehand.
When you assign ViewBag.SomeProperty = value;
, the runtime dynamically creates an entry for SomeProperty
in the ViewData
dictionary. The ViewBag
acts as a wrapper, intercepting calls to properties and storing them in ViewData
.
Example:
ViewBag.Greeting = "Hello!";
// Internally translates to: ViewData["Greeting"] = "Hello!";
When you try to access ViewBag.Greeting
, the framework dynamically checks if a corresponding entry exists in ViewData
and retrieves it. If it doesn’t exist, a runtime error occurs.
ViewBag
when you want concise and clean code for passing small amounts of data dynamically.ViewData
when you:
argument vs parameter
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.
// C# program to illustrate encapsulation
using System;
public class DemoEncap {
// private variables declared
// these can only be accessed by
// public methods of class
private String studentName;
private int studentAge;
// using accessors to get and
// set the value of studentName
public String Name
{
get { return studentName; }
set { studentName = value; }
}
// using accessors to get and
// set the value of studentAge
public int Age
{
get { return studentAge; }
set { studentAge = value; }
}
}
// Driver Class
class GFG {
// Main Method
static public void Main()
{
// creating object
DemoEncap obj = new DemoEncap();
// calls set accessor of the property Name,
// and pass "Ankita" as value of the
// standard field 'value'
obj.Name = "Ankita";
// calls set accessor of the property Age,
// and pass "21" as value of the
// standard field 'value'
obj.Age = 21;
// Displaying values of the variables
Console.WriteLine(" Name : " + obj.Name);
Console.WriteLine(" Age : " + obj.Age);
}
}
Encapsulation is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and the methods that operate on that data within a single unit. In C#, this is typically achieved through the use of classes.
The idea behind encapsulation is to keep the implementation details of a class hidden from the outside world, and to only expose a public interface that allows users to interact with the class in a controlled and safe manner. This helps to promote modularity, maintainability, and flexibility in the design of software systems.
A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another.
DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer. The main benefit here is that it reduces the amount of data that needs to be sent across the wire in distributed applications. They also make great models in the MVC pattern.
Another use for DTOs can be to encapsulate parameters for method calls. This can be useful if a method takes more than four or five parameters.
Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves code organization.
For any bird, there are a set of predefined properties which are common for all the birds and there are a set of properties which are specific for a particular bird. Therefore, intuitively, we can say that all the birds inherit the common features like wings, legs, eyes, etc. Therefore, in the object-oriented way of representing the birds, we first declare a bird class with a set of properties which are common to all the birds. By doing this, we can avoid declaring these common properties in every bird which we create. Instead, we can simply inherit the bird class in all the birds which we create. The following is an example of how the concept of inheritance is implemented.
The word polymorphism is made of two words poly and morph, where poly means many and morphs means forms. In programming, polymorphism is a feature that allows one interface to be used for a general class of actions. In the above concept of a bird and pigeon, a pigeon is inherently a bird. And also, if the birds are further categorized into multiple categories like flying birds, flightless birds, etc. the pigeon also fits into the flying bird’s category. And also, if the animal class is further categorized into plant-eating animals and meat-eating animals, the pigeon again comes into the plant-eating animal’s category. Therefore, the idea of polymorphism is the ability of the same object to take multiple forms. There are two types of polymorphism:
Data abstraction is a design pattern in which data are visible only to semantically related functions, to prevent misuse. The success of data abstraction leads to frequent incorporation of data hiding as a design principle in object-oriented and pure functional programming.
Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding).
While encapsulation groups together data and methods that act upon the data, data abstraction deal with exposing to the user and hiding the details of implementation.
StackOverflow:
https://stackoverflow.com/questions/15176356/difference-between-encapsulation-and-abstraction
Encapsulation hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.
Abstraction is used to hide something too, but in a higher degree (class, interface). Clients who use an abstract class (or interface) do not care about what it was, they just need to know what it can do.
Abstraction in general means hiding. In the above scenario of the bird and pigeon, let’s say there is a user who wants to see pigeon fly. The user is simply interested in seeing the pigeon fly but not interested in how the bird is actually flying. Therefore, in the above scenario where the user wishes to make it fly, he will simply call the fly method by using **pigeon.fly()** where the pigeon is the object of the bird pigeon. Therefore, abstraction means the art of representing the essential features without concerning about the background details. In Java, the abstraction is implemented through the use of interface and abstract classes. We can achieve complete abstraction with the use of Interface whereas a partial or a complete abstraction can be achieved with the use of abstract classes. The reason why abstraction is considered as one of the important concepts is: